<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>伊甸园停车场自助缴费服务</title>
    <link rel="stylesheet" href="../css/weui.css" />
    <link rel="stylesheet" href="../css/example.css" />
    <link rel="stylesheet" href="../css/plate.css" />
    <script src="../js/jquery-1.11.3.min.js"></script>
    <style>
        .cell_text:before,
        .cell_text:after {
            content: none;
        }

        .provienceBox {
            top: 0px;
            /* bottom: 0px; */
        }

        .add {
            font-size: 16px;
            display: block;
            margin: 0em 0em 0.8em 0em;
        }

        .history_plates {
            font-size: 16px;
            color: white;
            background-color: #0051BC;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 10px;
        }
    </style>
</head>

<body>
    <div class="content">
        <div class="weui-cells cell_text">
            <div class="weui-cell">
                <span>请点击方框输入车牌号：</span>
            </div>
            <div class="weui-cell cell_text">
                <div class="inpu">
                    <ul>
                        <li style="background:#F1F8FF;">粤</li>
                        <li>T</li>
                        <li class="active"></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li></li>
                        <li class="xinnengyuan"></li>
                    </ul>
                </div>
            </div>


        </div>
        <div class="button-sp-area">
            <a id="bind_car" class="weui-btn btn-same renew-btn">绑定车辆</a>
        </div>
        <!-- <span class="dot">●</span>         -->
    </div>
    <!-- 增加 历史车牌 -->
    <div class="weui-cells cell_text">
        <div class="weui-cell cell_text">
            <div class="weui-cell__bd">
                <span>历史车牌记录</span>
            </div>
            <div id="delete" class="weui-cell__ft">
                <img src="../images/del.@2x.png" alt="" style="width:15px;">
            </div>
        </div>
        <div class="weui-cell add">

        </div>

    </div>
    <!-- 键盘 -->
    <div id="keyboardBox">
        <div class="provienceBox" id="provienceBox">
            <ul>
                <li>京</li>
                <li>津</li>
                <li>渝</li>
                <li>沪</li>
                <li>冀</li>
                <li>晋</li>
                <li>辽</li>
                <li>吉</li>
                <li>黑</li>
                <li>苏</li>
            </ul>
            <ul>
                <li>浙</li>
                <li>皖</li>
                <li>闽</li>
                <li>赣</li>
                <li>鲁</li>
                <li>豫</li>
                <li>鄂</li>
                <li>湘</li>
                <li>粤</li>
                <li>琼</li>
            </ul>
            <ul>
                <li>川</li>
                <li>贵</li>
                <li>云</li>
                <li>陕</li>
                <li>甘</li>
                <li>青</li>
                <li>蒙</li>
                <li>桂</li>
                <li>宁</li>
                <li>新</li>
            </ul>
            <ul>
                <li class="changeContentBtn other">ABC</li>
                <li>藏</li>
                <li>使</li>
                <li>领</li>
                <li>警</li>
                <li>学</li>
                <li>港</li>
                <li>澳</li>
                <li class="deleteBtn other"><img src="../images/backDel@2x.png" /></li>
            </ul>
        </div>
        <div class="textBox" id="textBox">
            <ul>
                <li>1</li>
                <li>2</li>
                <li>3</li>
                <li>4</li>
                <li>5</li>
                <li>6</li>
                <li>7</li>
                <li>8</li>
                <li>9</li>
                <li>0</li>
            </ul>
            <ul>
                <li>Q</li>
                <li>W</li>
                <li>E</li>
                <li>R</li>
                <li>T</li>
                <li>Y</li>
                <li>U</li>
                <li>P</li>
            </ul>
            <ul>
                <li>A</li>
                <li>S</li>
                <li>D</li>
                <li>F</li>
                <li>G</li>
                <li>H</li>
                <li>J</li>
                <li>K</li>
                <li>L</li>
            </ul>
            <ul>
                <li class="changeContentBtn other">返回</li>
                <li>Z</li>
                <li>X</li>
                <li>C</li>
                <li>V</li>
                <li>B</li>
                <li>N</li>
                <li>M</li>
                <li class="deleteBtn other"><img src="../images/backDel@2x.png" /></li>
            </ul>
        </div>
    </div>
    <script type="text/javascript" src="../js/common.js"></script>
    <script type="text/javascript" src="../js/input_plate.js"></script>
    <script text="text/javascript" src="../js/base64.js"></script>
    <script text="text/javascript" src="../js/jquery-ui.js"></script>
    <script text="text/javascript" src="../js/get_plate.js"></script>

    <script>
        const auth_code = get_querystring("code");
        // alert('auth_code'+ auth_code);
        const state = get_querystring("state");
        var area = null;
        //openid是空的
        var openid = null;
        var plate = null;

        //获取车辆信息 --- 车牌号
        function getplate() {
            var plate = '';
            var isnext = true;
            var len = $('.inpu ul li').length;
            for (var i = 0; i < len; i++) {
                var value = $('.inpu ul li').eq(i).html();
                if (i == 0) {
                    if (!isChn(value) && !isInteger(value)) {
                        alert('车牌格式不正确');
                        isnext = false;
                        return;
                    }
                } else if (i == 1) {
                    if (!isBig(value) && !isInteger(value)) {
                        alert('车牌格式不正确');
                        isnext = false;
                        return;
                    }
                } else if ((i >= 2) && (i <= 5)) {
                    if (!isInteger(value) && !isBig(value)) {
                        alert('车牌格式不正确');
                        isnext = false;
                        return;
                    }
                } else if (i == 6) {
                    if (!isInteger(value) && !isBig(value) && value != '警' && value != '学' && value != '使') {
                        alert('车牌格式不正确');
                        isnext = false;
                        return;
                    }
                } else if (i == 7) {
                    if (!$('.inpu ul li').eq(i).hasClass('xinnengyuan')) {
                        if (!isInteger(value) && !isBig(value) && value != '警' && value != '学' && value != '使') {
                            alert('车牌格式不正确');
                            isnext = false;
                            return;
                        }
                        var prevalue = $('.inpu ul li').eq(i - 1).html();
                        if (!isInteger(prevalue) && !isBig(prevalue)) {
                            alert('车牌格式不正确');
                            isnext = false;
                            return;
                        }
                    }
                }

                plate += value;
            }
            var plateData = {};
            plateData.plate = plate;
            plateData.bool = isnext;
            return plateData;
        }


        // 车牌号 判断 是否符合规范
        function get_plate() {
            var plate = '';
            var isnext = true;
            var len = $('.inpu ul li').length;
            for (var i = 0; i < len; i++) {
                var value = $('.inpu ul li').eq(i).html();
                if (i == 0) {
                    if (!isChn(value) && !isInteger(value)) {
                        alert("车牌格式不正确");
                        isnext = false;
                        return;
                    }
                } else if (i == 1) {
                    if (!isBig(value) && !isInteger(value)) {
                        alert("车牌格式不正确");
                        isnext = false;
                        return;
                    }
                } else if ((i >= 2) && (i <= 5)) {
                    if (!isInteger(value) && !isBig(value)) {
                        alert("车牌格式不正确");
                        isnext = false;
                        return;
                    }
                } else if (i == 6) {
                    if (!isInteger(value) && !isBig(value) && value != '警' && value != '学' && value != '使') {
                        alert("车牌格式不正确");
                        isnext = false;
                        return;
                    }
                } else if (i == 7) {
                    if (!$('.inpu ul li').eq(i).hasClass('xinnengyuan')) {
                        if (!isInteger(value) && !isBig(value) && value != '警' && value != '学' && value != '使') {
                            alert("车牌格式不正确");
                            isnext = false;
                            return;
                        }
                        var prevalue = $('.inpu ul li').eq(i - 1).html();
                        if (!isInteger(prevalue) && !isBig(prevalue)) {
                            alert("车牌格式不正确");
                            isnext = false;
                            return;
                        }
                    }
                }

                plate += value;
            }
            return isnext && plate;
        }

        //获取用户的信息
        //根据用户唯一的openid来获得相关的一切信息
        function get_user() {
            $.ajax({
                type: "GET",
                timeout: 3 * 1000,
                url: `${hostname}${rest_domain}/wechat/user/usermanager?openid=${openid}`,
                success: function (result, status) {
                    if (!result || !result.result) {
                        alert('连接成功 ，获取用户信息失败！')
                        return;
                    }
                    userinfo = result.data;
                    //如果此时的userinfo.plates是空的，
                    if (!userinfo.plates) {
                        userinfo.plates = {};
                    }
                    localStorage.setItem("userinfo", JSON.stringify(userinfo));
                    // alert(localStorage.getItem('userinfo'));

                    //用户不存在，则创建新的内容为空的用户
                    if (!userinfo.exist) {
                        alert('获取不到用户的信息，即将创建一个新的用户！');
                        create_user();
                    }

                    var history_plates = userinfo.history_plates;
                    drawuserplates(history_plates);

                },
                error: function () {
                    alert('连接get_user()函数失败！！');
                }
            });
        }

        //创建用户
        function create_user() {
            var data = {
                openid: openid,
            };
            $.ajax({
                type: "POST",
                timeout: 3 * 1000,
                url: `${hostname}${rest_domain}/wechat/user/usermanager`,
                data: JSON.stringify(data),
                dataType: "json",
                success: function (result, status) {
                    if (!result || !result.result) {
                        $('.weui-dialog__bd').html(result && result.message || '添加用户信息失败');
                        $('#tipdialog').fadeIn(200);
                        return;
                    }

                    //创建用户之后，获取用户信息
                    get_user();
                },
                error: function () {
                    $('.weui-dialog__bd').html('连接失败');
                    $('#tipdialog').fadeIn(200);
                }
            });
        }

        //获取微信用户的openid
        function get_openid() {
            $.ajax({
                type: "GET",
                timeout: 3 * 1000,
                url: `${hostname}${rest_domain}/wechat/user/openid?code=${auth_code}`,
                success: function (result, status) {
                    if (!result || !result.result) {
                        alert('从微信中获取用户信息失败');
                        return;
                    }
                    //返回的result.data
                    openid = result.data;
                    localStorage.setItem("openid", openid);
                    get_user();

                },
                error: function () {
                    alert('get_openid()连接失败！！！');
                }
            });
        }

        //添加车牌号
        function addplate() {
            var inputvalue = getplate();
            if ((!inputvalue) || (!inputvalue.bool)) {
                $('.inpu li').each(function (n) {
                    $(this).html('');
                    $(this).removeClass('active');
                    if (n == 7) {
                        $(this).addClass('xinnengyuan');
                    }
                });
                $('.inpu li').eq(0).addClass('active');
                $('#textBox').hide();
                $('#provienceBox').show();
                return;
            }

            var car = inputvalue.plate;
            deletecar(car);

            var adddata = {
                openid: openid,
                plate: inputvalue.plate,
            };
            $.ajax({
                type: 'post',
                url: `${hostname}${rest_domain}/wechat/user/plates`,
                data: JSON.stringify(adddata),
                dataType: "json",
                success: function (result, textStatus) {
                    if (!result || !result.result) {
                        // alert('未找到车辆信息');
                        return;
                    }
                    var uesrinfo = JSON.parse(localStorage.getItem('userinfo'));
                    uesrinfo.plates[inputvalue.plate] = { "prefer": 0 };
                    localStorage.setItem('userinfo', JSON.stringify(uesrinfo));
                    next(inputvalue.plate)
                    window.location.href = payurl;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert('addplate failed!!!');
                }
            });
        }


        //删除全部绑定的车辆信息
        function deletecar(plate) {
            var deldata = {
                openid: openid,
                plate: plate
            };
            //需要删除车辆的地址
            var delplateurl = hostname + rest_domain + '/wechat/user/plates';

            //请求是delete类型的
            //将json数据转换成js字符串类型
            $.ajax({
                type: 'delete',
                url: delplateurl,
                data: JSON.stringify(deldata),
                dataType: "json",
                success: function (result, textStatus) {
                    if (!result || !result.result) {
                        $('.weui-dialog__bd').html(result && result.message || '车辆删除失败');
                        $('#tipdialog').fadeIn(200);
                        return;
                    }
                    var uesrinfo = JSON.parse(localStorage.getItem('userinfo'));
                    delete uesrinfo.plates[plate];
                    localStorage.setItem('userinfo', JSON.stringify(uesrinfo));
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // alert('delete failed ... ');

                }
            });
        }

        //查询用户的车牌
        // function queryuserplates() {
        //     var querydata = {
        //         openid: openid
        //     };
        //     var userplateurl = hostname + rest_domain + '/wechat/user/plates';
        //     $.ajax({
        //         type: 'get',
        //         url: userplateurl,
        //         timeout: 5 * 1000,
        //         data: querydata,
        //         success: function (result, textStatus) {
        //             if (!result || !result.result) {
        //                 alert('there is no data in queryuserplate');
        //                 return;
        //             }
        //             alert(JSON.stringify(result));
        //             openid = result.data.openid;
        //             localStorage.setItem("openid", openid);
        //             var history_plates = JSON.parse(userinfo).history_plates;
        //             drawuserplates(history_plates);

        //         },
        //         error: function (XMLHttpRequest, textStatus, errorThrown) {
        //             alert('连接失败！！！');
        //         }
        //     });
        // }


        function drawuserplates(data) {
            //传递的是一个对象的时候
            // var car = $("<div 'class = weui-cell  add'><span>进入</span><div>").html('进入车辆：' + data);
            // $(".add").append(car);
            // car.addClass('history_plates');
            // $('.add').on("click", function () {

            //     window.location.href = 'nomoney_car.html';
            // });

            //当传递的是一个数组的时候，需要进行遍历插入新的元素
            var length = 0;
            for (var i = data.length - 3; i < data.length; i++) {
                var car = $("<div 'class = weui-cell  add'><div>").html('进入车辆：' + data[i]);
                $(".add").append(car);
                car.addClass('history_plates');
                length = i;
            }
            if (length >= 2) {
                $('#keyboardBox').height(10 * i);
            }
            $('.history_plates').on('click', function () {
                for (var i = data.length - 1; i >= 0; i--) {
                    deletecar(data[i]);
                }
                var historyplate = $(this).html();
                var history_plate = historyplate.substr(5);
                next(history_plate);
                pagejump(history_plate);
            })
        }

        function next(plate) {
            //如果车牌号为0,直接返回
            if (!plate)
                return;
            //将车牌号存为页面缓存
            sessionStorage.setItem('pay_plate', plate);
            payurl = `expired_monthcard.html?plate=${plate}&state=${state}`;
            // payurl = `nomoney_car.html?plate=${plate}&state=${state}`;
            //访问的的地址加上plate和state
            //openid是存在的，加上openid
            //如果不存在openid，加上auth_code
            payurl += `&openid=${openid}`;
            payurl += `&auth_code=${auth_code}`;

        }

        function pagejump(history_plate) {
            var jumpdata = {
                openid: openid,
                plate: history_plate
            };

            $.ajax({
                type: 'post',
                url: `${hostname}${rest_domain}/wechat/user/plates`,
                data: JSON.stringify(jumpdata),
                dataType: "json",
                success: function (result, textStatus) {
                    if (!result || !result.result) {
                        return;
                    }
                    var uesrinfo = JSON.parse(localStorage.getItem('userinfo'));
                    uesrinfo.plates[history_plate] = { "prefer": 0 };
                    localStorage.setItem('userinfo', JSON.stringify(uesrinfo));
                    window.location.href = payurl;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert('change failed!!!');
                }
            });

        }

        $(function () {
            var local_auth_code = localStorage.getItem("auth_code");

            if (local_auth_code != auth_code || !openid) {
                localStorage.clear();
                //将auth_code和state放在本地缓存中
                localStorage.setItem("auth_code", auth_code);
                localStorage.setItem("state", state);
                get_openid();
                //这个也是一个查询的函数
                // queryplate();
            }
            else {

                alert('用户的信息为空，此时创建一个新的空用户！');
                //如果用户的信息为空，就创建用户
                if (!userinfo) {
                    get_user();
                    return;
                }

                userinfo = JSON.parse(userinfo);
                $("#tel").html(userinfo.phone || "请验证您的手机号");

                if (userinfo.wechat) {
                    var nickname = userinfo.wechat.nickname;
                    var headimgurl = userinfo.wechat.headimgurl;

                    $("#head_image").prop("src", headimgurl);
                    $("#username").html(nickname);
                }
            }


            $("#delete").on("click", function () {
                var uesrinfo = JSON.parse(localStorage.getItem('userinfo'));
                var plates = userinfo.plates;
                var plate = getplate().plate;
                for (var key in plates) {
                    deletecar(key);
                }
                alert(JSON.stringify(userinfo));
            });


            $("#bind_car").on("click", function () {
                // 绑定车辆
                addplate();
                //临停车辆
                // window.location.href = encodeURI("temp_car.html?car_num="+car_num);
                //储值卡用户
                // window.location.href = encodeURI("nomoney_car.html?car_num=" + car_num);
            });
        })
    </script>
</body>

</html>